package com.k12.admim.exception;

import cn.dev33.satoken.exception.NotLoginException;
import com.k12.common.model.resp.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    
    // 拦截所有未处理的异常
    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e, HttpServletRequest  request) {
        String uri = request.getRequestURI();
        log.error("全局异常信息,异常接口地址为:{},异常信息为:",uri , e);
        return R.failed(500, e.getMessage());
    }
    
    // 拦截未登录异常
    @ExceptionHandler(NotLoginException.class)
    public R<String> handleNotLoginException(NotLoginException nle, HttpServletRequest request) {
        // 不同情况返回不同的状态码
        String message = "";
        String uri = request.getRequestURI();
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            log.error("未登录异常,异常接口地址为:{},异常信息为:",uri , nle);
            message = "未登录，请先登录";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "Token无效";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "Token已过期";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "Token已被顶下线";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "Token已被踢下线";
        } else {
            message = "当前会话未登录";
        }
        return R.failed(401, message);
    }
}